package plugins.schoolcard;

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.BillShowParameter;
import kd.bos.cache.CacheFactory;
import kd.bos.cache.DistributeSessionlessCache;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.CloseCallBack;
import kd.bos.form.ShowType;
import kd.bos.form.control.Toolbar;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.sdk.plugin.Plugin;

import java.math.BigDecimal;
import java.util.EventObject;

public class toCharge extends AbstractBillPlugIn implements Plugin {

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        Toolbar toolbar = this.getControl("tbmain");
        toolbar.addItemClickListener(this);
    }

    @Override
    public void itemClick(ItemClickEvent evt) {
        super.itemClick(evt);
        String itemKey = evt.getItemKey();

        if ("dcb4_recharge".equals(itemKey)) {

            String status = (String) this.getModel().getValue("dcb4_status");

            if ("C".equals(status)) {
                // 状态为C，中止操作并提示
                this.getView().showMessage("当前账户已冻结，请联系管理员");
                return;
            }

            if ("A".equals(status)) {
                // 状态不是B，中止操作并提示
                this.getView().showMessage("当前账户未激活，请先激活");
                return;
            }

            // 使用分布式无会话缓存
            DistributeSessionlessCache cache = CacheFactory.getCommonCacheFactory().getDistributeSessionlessCache("customRegion");

            // 缓存操作
            String numberValue = (String) this.getModel().getValue("number");
            cache.put("schoolcardnumber", numberValue);
            cache.put("schoolcardtag", "recharge");

            // 显示缓存键

            // 跳转到目标单据（模态框）
            BillShowParameter showParameter = new BillShowParameter();
            showParameter.setFormId("dcb4_cardhistory");
            showParameter.getOpenStyle().setShowType(ShowType.Modal);

            // 设置回调标识
            showParameter.setCloseCallBack(new CloseCallBack(this, "afterTargetBillClosed"));
            this.getView().showForm(showParameter);
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
        super.closedCallBack(closedCallBackEvent);

        // 检查是否是目标页面关闭的回调
        if ("afterTargetBillClosed".equals(closedCallBackEvent.getActionId())) {
            // 获取当前单据的实体标识（表单ID）
            String entityNumber = this.getView().getFormShowParameter().getFormId();

            // 获取当前单据的主键值
            DynamicObject dataEntity = this.getModel().getDataEntity(true);
            Object pkId = dataEntity.getPkValue();

            // 执行反审核操作
            OperationResult result = OperationServiceHelper.executeOperate(
                    "unaudit",  // 反审核操作标识
                    entityNumber,
                    new Object[]{pkId}
            );


            if (result.isSuccess()) {
                // this.getView().showSuccessNotification("单据已成功反审核");

                // 从缓存中获取 schoolcardamount 数据
                DistributeSessionlessCache cache = CacheFactory.getCommonCacheFactory().getDistributeSessionlessCache("customRegion");
                String amountStr = cache.get("schoolcardamount");

                if (amountStr != null && !amountStr.isEmpty()) {
                    try {
                        // 将字符串转换为 BigDecimal
                        BigDecimal amount = new BigDecimal(amountStr);

                        // 获取当前单据的金额字段值
                        BigDecimal currentAmount = (BigDecimal) this.getModel().getValue("dcb4_amount");
                        if (currentAmount == null) {
                            currentAmount = BigDecimal.ZERO;
                        }

                        // 将缓存中的金额加到当前金额上
                        BigDecimal newAmount = currentAmount.add(amount);

                        // 更新单据的金额字段
                        this.getModel().setValue("dcb4_amount", newAmount);

                        // 刷新界面显示
                        this.getView().updateView();

                        this.getView().showMessage("充值成功");
                    } catch (NumberFormatException e) {
                        this.getView().showErrorNotification("金额格式错误: " + amountStr);
                    }
                } else {
                    this.getView().showTipNotification("未找到缓存中的金额数据");
                }
            } else {
                this.getView().showErrorNotification("反审核失败：" + result.getMessage());
            }
        }
    }
}
